package com.ks.phone.base;

import android.util.Log;

import androidx.annotation.NonNull;

import com.ks.phone.provider.ContextGlobal;
import com.ks.phone.utils.FileUtils;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class AppCrashHandler implements Thread.UncaughtExceptionHandler {
    private static volatile AppCrashHandler singleton = null;
    private static final String CRASH_LOG_FILE_NAME = "XPhone_crash_log.txt";

    private AppCrashHandler() {
    }

    public static AppCrashHandler getInstance() {
        if (singleton == null) {
            synchronized (AppCrashHandler.class) {
                if (singleton == null) {
                    singleton = new AppCrashHandler();
                }
            }
        }
        return singleton;
    }


    @Override
    public void uncaughtException(@NonNull Thread t, @NonNull Throwable e) {
        // 生成崩溃报告
        String crashLog = generateCrashLog(e);
        // 存储崩溃报告到本地文件
        saveCrashLogToFile(crashLog);
    }

    public void init() {
        Thread.setDefaultUncaughtExceptionHandler(singleton);
    }

    private String generateCrashLog(Throwable throwable) {
        StringBuilder sb = new StringBuilder();

        // 添加时间戳
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
        String timestamp = sdf.format(new Date());
        sb.append("Crash Timestamp: ").append(timestamp).append("\n\n");

        // 添加异常堆栈信息
        sb.append("Exception Stack Trace:\n");
        sb.append(throwable.toString()).append("\n");
        for (StackTraceElement element : throwable.getStackTrace()) {
            sb.append(element.toString()).append("\n");
        }

        return sb.toString();
    }

    private void saveCrashLogToFile(String crashLog) {
        // 存储路径：/storage/emulated/0/Android/data/cictci.netcar2d.cjyh/files/crash
        String crash_log_path = ContextGlobal.get().getApplicationContext().getExternalFilesDir(null) + "/crash";
        File rootDir = new File(crash_log_path);
        if (rootDir != null && !rootDir.exists()) {
            boolean mkdirs = rootDir.mkdirs();
            if (!mkdirs) return;
        }
        if (rootDir != null) {
            File crashLogFile = new File(rootDir, CRASH_LOG_FILE_NAME);
            Log.d("crash_handler", "saveCrashLogToFile: " + crashLogFile.getAbsolutePath());
            long length = crashLogFile.length();
            // 如果长度大于1M，则清空文件
            if (length > 1 * 1024f * 1024f) {
                FileUtils.cleanFileContent(crashLogFile);
            }
            FileUtils.saveContentToFile(crashLog, crashLogFile, true);
        }
    }
}
